<template>
  <div>
    <a-modal :visible="visible" :title="type == 'add' ? '创建其他入库单' : '编辑其他入库单'" @before-open="open" :on-before-ok="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" width="1200px" :mask-closable="false">
      <div>
        <a-form auto-label-width ref="formRef" size="medium" :model="form">
          <a-space direction="vertical" :size="24">
            <a-row>
              <a-col :span="10">
                <a-form-item field="warehouseCode" label="选择仓库" :rules="rules.warehouseCode">
                  <a-select @change="selHouse" :disabled="type == 'edit'" v-model="form.warehouseCode" placeholder="请选择仓库" allow-clear allow-search>
                    <a-option v-for="item of houseList" :label="item.warehouseName" :value="item.warehouseCode"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="14">
                <a-form-item field="shopId" label="店铺" :rules="rules.shopId">
                  <a-select @change="selShop" :disabled="type == 'edit'" v-model="form.shopId" placeholder="请选择店铺" allow-clear allow-search>
                    <a-option v-for="item of shopList" :label="item.shopName" :value="item.sellerMarketId"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-item field="remark" label="备注">
                  <a-input v-model="form.remark" placeholder="请输入备注"></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-space>
        </a-form>
      </div>
      <div>
        <a-button size="medium" type="primary" @click="addProduct">添加入库产品</a-button>
        <span style="margin-left: 10px">SKU种类：</span><span>{{ skuKind }}</span> <span style="margin-left: 10px">入库数量：</span><span>{{ inHouseNum }}</span> <span style="margin-left: 10px">总金额：</span><span>￥{{ allPrice }}</span>

        <a-table :pagination="false" size="mini" class="table-two-line" style="margin-top: 10px" :columns="columns" :data="tableList" :scroll="{ x: '100%', y: '400px' }">
          <template #columns>
            <a-table-column title="货主" :width="150">
              <template #cell="{ record, rowIndex }">
                <a-space>
                  <a-select placeholder="请选择" allow-clear allow-search style="width: 100px" @change="changeUSer($event, record)" v-model="record.ownerId">
                    <a-option v-for="(item, index) of userList" :label="item.userName" :value="item.id" :key="index"></a-option>
                  </a-select>
                  <a-button size="small" class="gray-outline" @click="setPro('ownerId', record, rowIndex)">
                    <template #icon>
                      <icon-double-down />
                    </template>
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
            <a-table-column title="图片" :width="60">
              <template #cell="{ record }">
                <ImgPopover :src="getImgSrc(record)">
                  <template #con>
                    <a-image :preview="false" width="40" height="40" fit="contain" :src="getImgSrc(record)" />
                  </template>
                </ImgPopover>
                <!-- <a-image width="40px" :src="getImgSrc(record)" /> -->
                <!-- <span v-if="form.shopId != 'shareshop'"><a-image width="60px" :src="record.imageList && record.imageList[0] ? record.imageList[0].link : ''" /></span>
                <span v-else><a-image width="60px" v-if="record.productPicList && record.productPicList[0]" :src="record.productPicList[0].url" /></span> -->
              </template>
            </a-table-column>
            <a-table-column title="产品名称/SKU" :width="160">
              <template #cell="{ record }">
                <a-popover>
                  <div v-if="!shopInfo.share">
                    <div class="text-limit">{{ $extract(record, 'product.sku') }}</div>
                    <div class="text-limit">{{ $extract(record, 'product.skuName') }}</div>
                  </div>
                  <div v-else>
                    <div class="text-limit">{{ record.skuName }}</div>
                    <div class="text-limit">{{ record.sku }}</div>
                  </div>
                  <template #content>
                    <div v-if="!shopInfo.share">
                      <div>{{ $extract(record, 'product.sku') }}</div>
                      <div>{{ $extract(record, 'product.skuName') }}</div>
                    </div>
                    <div v-else>
                      <div class="text-limit">{{ record.skuName }}</div>
                      <div class="text-limit">{{ record.sku }}</div>
                    </div>
                  </template>
                </a-popover>
              </template>
            </a-table-column>
            <a-table-column title="MSKU" :width="160">
              <template #cell="{ record, rowIndex }">
                <div v-if="shopInfo.share">
                  <div>{{ record.sku }}</div>
                </div>
                <div v-else>
                  <div>{{ record.msku }}</div>
                  <!-- <div>{{ record.fnSku }}</div> -->
                </div>
              </template>
            </a-table-column>
            <a-table-column title="SPU/类目" :width="140">
              <template #cell="{ record, rowIndex }">
                <div v-if="!shopInfo.share">
                  <div>{{ record.spu }}</div>
                  <div v-if="record.category">{{ record.category.name }}</div>
                </div>
                <div v-else>
                  <div>{{ record.spu }}</div>
                  <div v-if="record.category">{{ record.category.name }}</div>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="品牌" :width="60">
              <template #cell="{ record, rowIndex }">
                <div v-if="shopInfo.share">
                  <div v-if="record.brand">{{ record.brand.name }}</div>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="产品类型" :width="80">
              <template #cell="{ record, rowIndex }">
                <div v-if="shopInfo.share">
                  <div>{{ record.productType == 'normal' ? '普通产品' : '组合产品' }}</div>
                </div>
                <div v-else>
                  <div>{{ record.saleType }}</div>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="数量" :width="140">
              <template #cell="{ record, rowIndex }">
                <div style="display: flex">
                  <a-input-number :min="1" style="width: 100px" v-model="record.amt" hide-button />
                  <a-button size="small" class="gray-outline" style="margin-left: 5px" @click="setPro('amt', record, rowIndex)">
                    <template #icon>
                      <icon-double-down />
                    </template>
                  </a-button>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="入库属性" :width="140">
              <template #cell="{ record, rowIndex }">
                <div style="display: flex">
                  <a-select placeholder="请选择" style="width: 100px" v-model="record.attribute">
                    <a-option label="良品" value="good"></a-option>
                    <a-option label="次品" value="defective"></a-option>
                  </a-select>
                  <a-button size="small" class="gray-outline" style="margin-left: 5px" @click="setPro('attribute', record, rowIndex)">
                    <template #icon>
                      <icon-double-down />
                    </template>
                  </a-button>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="单位成本" :width="140">
              <template #cell="{ record, rowIndex }">
                <div style="display: flex">
                  <a-input-number v-model="record.price" hide-button />
                  <a-button size="small" class="gray-outline" style="margin-left: 5px" @click="setPro('price', record, rowIndex)">
                    <template #icon>
                      <icon-double-down />
                    </template>
                  </a-button>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="货值" :width="120">
              <template #cell="{ record }">
                <span>{{ record.amt * record.price }}</span>
              </template>
            </a-table-column>
            <a-table-column title="上架货位" :width="140">
              <template #cell="{ record, rowIndex }">
                <div style="display: flex">
                  <a-select style="width: 100px" placeholder="请选择" @change="singleSelLocationCode($event, record)" v-model="record.locationCode" allow-search>
                    <a-option v-for="item of houseLocationList" :label="item.locationCode" :value="item.locationCode"></a-option>
                  </a-select>
                  <a-button size="small" class="gray-outline" style="margin-left: 5px" @click="setPro('locationCode', record, rowIndex)">
                    <template #icon>
                      <icon-double-down />
                    </template>
                  </a-button>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="操作" :width="60">
              <template #cell="{ record, rowIndex }">
                <a-button type="text" size="medium" @click="tableList.splice(rowIndex, 1)">移除</a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
  <SelProduct ref="productlist" :shopInfo="shopInfo" @save="saveProduct" />
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed, h } from 'vue'
  import { findWarehouseListByParam, findShopListByShare, findIdleLocationByWarehouse, updateOtherIn, findAvailableLocation, createOtherIn, getOtherInInfo } from '@/api/warehouse'
  import SelProduct from './selInhouseProduct.vue'
  import { IconSearch } from '@arco-design/web-vue/es/icon'
  import { Message } from '@arco-design/web-vue'
  import { getOrganizesUser } from '@/api/system'
  import ImgPopover from '@/components/imgPopover.vue'
  export default defineComponent({
    props: ['type', 'id'],
    components: {
      SelProduct,
      ImgPopover,
    },
    setup(props: any, { emit }) {
      let visible = ref(false)
      const formRef = ref()
      const productlist = ref()
      const data: any = reactive({
        titleFormValue: {
          amt: '',
          price: '  ',
          attribute: 'good',
          locationCode: 'Z',
        },
        form: {
          shopId: 'shareshop',
          shopName: '共享',
        },
        rules: {
          warehouseCode: [{ required: true, message: '请选择仓库' }],
          shopId: [{ required: true, message: '请选择店铺' }],
        },
        tableList: [],
        shopList: [],
        houseList: [],
        columns: [
          {
            title: '图片',
            dataIndex: 'name',
            // fixed: 'left',
            width: 140,
          },
          {
            title: 'Name',
            dataIndex: 'name',
            // fixed: 'left',
            width: 140,
          },
          {
            title: 'Name',
            dataIndex: 'name',
            // fixed: 'left',
            width: 140,
          },
        ],
        houseLocationList: [],
        shopInfo: {},
        userList: [],
      })

      const open = () => {
        getShopList()
        getWarehouseList()
      }

      const getDetail = async () => {
        const res = await getOtherInInfo({ id: props.id })
        data.form = res?.data || {}
        data.tableList = res?.data?.otherInItems || []
        // console.log(data.shopList, '222')
        let item: any = data.shopList.find((e: any) => e.sellerMarketId == data.form.shopId)
        if (item) data.shopInfo = item
      }

      const changeUSer = (val: string, info: any) => {
        let obj = data.userList.find((e: any) => e.id == val)
        if (obj) {
          info.ownerName = obj.userName
        } else {
          info.ownerName = ''
        }
      }

      const handleOk = (done: any) => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            if (data.tableList.length <= 0) {
              done(true)
              return Message.error('请添加入库货品')
            }
            let params = {
              ...data.form,
              otherInItems: [],
            }

            let res: any = {}
            data.tableList.forEach((e: any) => {
              let obj: any = {
                amt: e.amt,
                attribute: e.attribute,
                brandId: e.brand ? e.brand.id : '',
                brandName: e.brand ? e.brand.name : '',
                cateId: e.category ? e.category.id : '',
                cateName: e.category ? e.category.name : '',
                fnsku: '',
                locationCode: e.locationCode,
                locationId: e.locationId,
                ownerId: e.ownerId,
                ownerName: e.ownerName,
                msku: e?.msku || '',
                price: e.price,
                productId: e.id,
                productName: e?.skuName || '',
                productType: e?.productType || '',
                remark: '',
                sku: e?.product?.sku || e.sku,
                spu: e?.spu,
              }

              if (props.type == 'edit' && e.id) {
                obj.id = e.id
              }

              if (!data.shopInfo.share) {
                obj.productImg = e.imageList && e.imageList[0] ? e.imageList[0].link : ''
              } else {
                obj.productImg = e.productPicList && e.productPicList[0] ? e.productPicList[0].url : ''
              }

              if (props.type == 'edit') obj.productImg = e.productImg

              params.otherInItems.push(obj)
            })

            try {
              if (props.type == 'add') {
                res = await createOtherIn(params)
              } else {
                res = await updateOtherIn(params)
              }

              if (res.code == 'SUCCESS') {
                data.tableList = []
                formRef.value.clearValidate()
                props.type == 'add' ? Message.success('创建成功') : Message.success('更新成功')
                emit('save')
                visible.value = false
              }
              done(true)
            } catch (error) {
              done(true)
            }
          } else {
            done(true)
          }
        })
      }

      // 获取人员
      const getUserList = async () => {
        let params = {
          depart: false,
          needRole: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res = await getOrganizesUser(params)
        data.userList = res?.data?.records || []
      }

      const handleCancel = () => {
        formRef.value.clearValidate()
        // data.form = {
        //   shopId: 'shareshop',
        //   shopName: '共享',
        // }
        data.form = {}
        data.tableList = []
        visible.value = false
      }
      // 获取店铺列表
      const getShopList = async () => {
        const res = await findShopListByShare()
        data.shopList = res?.data || []
        data.form = {
          shopId: data.shopList[0].id,
          shopName: data.shopList[0].shopName,
          sellerId: data.shopList[0].sellerId,
          marketplaceId: data.shopList[0].marketplaceId,
        }

        data.shopInfo = data.shopList[0]
      }
      // 获取仓库列表
      const getWarehouseList = async () => {
        const res = await findWarehouseListByParam()
        data.houseList = res?.data || []
        if (props.type == 'edit') getDetail()
      }
      const getColumn = (data: any) => {
        console.log(data)
      }

      const selHouse = (val: string) => {
        if (val) {
          getSpaceList(val)
        } else {
          data.houseLocationList = []
        }
        let obj = data.houseList.find((e: any) => e.warehouseCode == val)
        data.form.warehouseName = obj.warehouseName
      }

      const selShop = (val: string) => {
        data.shopInfo = data.shopList.find((e: any) => e.sellerMarketId == val)
        // let obj = data.shopList.find((e: any) => e.id == val)
        data.form.shopName = data.shopInfo.shopName
        data.form.sellerId = data.shopInfo.sellerId
        data.form.marketplaceId = data.shopInfo.marketplaceId
        data.tableList = []
      }

      // productlist.visible = true
      const addProduct = () => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            productlist.value.visible = true
          }
        })
      }

      const saveProduct = (arr: any) => {
        if (data.tableList.length <= 0) {
          data.tableList = arr
        } else {
          arr.forEach((e: any) => {
            let index = data.tableList.findIndex((el: any) => el.id == e.id)
            if (index == -1) {
              data.tableList.push(e)
            }
          })
        }
        let params: any = {
          itemParams: [],
        }
        data.tableList.forEach((e: any) => {
          e.amt = e.amt ? e.amt : 1
          e.attribute = 'good'
          e.price = e.price ? e.price : ''
          e.locationCode = ''
          let obj = {
            attribute: 'good',
            msku: e.msku ? e.msku : '',
            shopId: data.form.shopId,
            sku: e.sku ? e.sku : '',
            warehouseCode: data.form.warehouseCode,
          }
          params.itemParams.push(obj)
        })
        getavailableLocation(params)
      }

      // 获取仓位列表
      const getSpaceList = async (val: string) => {
        const res = await findIdleLocationByWarehouse({ warehouseCode: val })
        data.houseLocationList = res?.data
      }

      // 批量查询可用货位
      const getavailableLocation = async (params: any) => {
        const res = await findAvailableLocation(params)
        res.data.forEach((e: any) => {
          data.tableList.forEach((el: any) => {
            if (e.sku == el.sku || e.msku == el.msku) {
              el.locationCode = e.locationList[0].locationCode
              el.locationId = e.locationList[0].id
            }
          })
        })

        console.log(data.tableList)
      }

      const setPro = (type: string, info: any, index: number) => {
        if (!info[type]) {
          Message.error('请输入或选择相应的值')
          return
        }

        let obj: any = {}
        if (type == 'locationCode') {
          obj = data.houseLocationList.find((e: any) => e.locationCode == info[type])
        }

        let obj2: any = {}
        if (type == 'ownerId') {
          obj2 = data.userList.find((e: any) => e.id == info[type])
        }

        data.tableList.forEach((e: any, i: number) => {
          if (type == 'locationCode') e.locationId = obj.id
          if (type == 'ownerId') e.ownerName = obj2.userName
          if (i >= index) e[type] = info[type]
        })

        console.log(data.tableList)
      }

      const singleSelLocationCode = (val: string, item: any) => {
        let obj = data.houseLocationList.find((e: any) => e.locationCode == val)
        item.locationId = obj.id
      }

      const getImgSrc = (item: any) => {
        let text = ''

        if (props.type == 'add') {
          if (!data.shopInfo.share) {
            item.imageList && item.imageList[0] ? (text = item.imageList[0].link) : (text = '')
          } else {
            item.productPicList && item.productPicList[0] ? (text = item.productPicList[0].url) : (text = '')
          }
        } else {
          console.log(item, '444444444444')

          text = item.productImg
        }
        return text
      }

      const skuKind = computed(() => {
        let skuArr: any = []
        data.tableList.forEach((e: any) => {
          let index = skuArr.findIndex((el: any) => el == e.sku || e.msku)
          if (index == -1) {
            skuArr.push(e?.sku || e?.msku)
          }
        })
        return skuArr.length
      })
      const allPrice = computed(() => {
        let allPrice = 0
        data.tableList.forEach((e: any) => {
          allPrice += e.price * e.amt
        })
        return allPrice
      })
      const inHouseNum = computed(() => {
        let num = 0
        data.tableList.forEach((e: any) => {
          num += e.amt
        })
        return num
      })

      getUserList()

      return {
        ...(toRefs(data) as any),
        visible,
        formRef,
        open,
        handleOk,
        handleCancel,
        getColumn,
        productlist,
        selHouse,
        selShop,
        addProduct,
        saveProduct,
        setPro,
        skuKind,
        allPrice,
        inHouseNum,
        singleSelLocationCode,
        getImgSrc,
        changeUSer,
      }
    },
  })
</script>

<style lang="less" scoped></style>
